package com.example.common_base.net;


import com.blankj.utilcode.util.LogUtils;

import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;

import okhttp3.FormBody;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.logging.HttpLoggingInterceptor;


public class InterceptorUtil {
    public final static Charset UTF8 = Charset.forName("UTF-8");
    public static String TAG = "http_log";

    //日志拦截器
    public static HttpLoggingInterceptor LogInterceptor() {
        return new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
            @Override
            public void log(String message) {
                LogUtils.json(TAG, message);
            }
        }).setLevel(HttpLoggingInterceptor.Level.BODY);//设置打印数据的级别
    }

    static String getMessageDigest(byte[] buffer) {
        char[] hexDigits = new char[]{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

        try {
            MessageDigest mdTemp = MessageDigest.getInstance("MD5");
            mdTemp.update(buffer);
            byte[] md = mdTemp.digest();
            int j = md.length;
            char[] str = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; ++i) {
                byte byte0 = md[i];
                str[k++] = hexDigits[byte0 >>> 4 & 15];
                str[k++] = hexDigits[byte0 & 15];
            }

            return new String(str);
        } catch (Exception var9) {
            return null;
        }
    }


    public static Interceptor headerParamsInterceptor() {
        return chain -> {
            Map<String, String> headerParams = new HashMap<>();
            headerParams.put("timestamp", String.valueOf(System.currentTimeMillis() / 1000));
            headerParams.put("nonce", UUID.randomUUID().toString().replace("-", ""));
            headerParams.put("token", "");
            headerParams.put("userid",  "");
            headerParams.put("appversion", "android.6.6.0");
            headerParams.put("sign", calcSign(headerParams, chain.request()));
//            if (AppUtils.getAppVersionName().split("\\.").length != 3) {
//                throw new UnsupportedOperationException("versionName 的格式必须遵循与服务端约定的 \"x.x.x\" (三位版本号)\n形如：5.3.0、6.0.0、7.0.0、8.1.0");
//            }
            Request.Builder mRequestBuilder = chain.request().newBuilder();
            for (String key : headerParams.keySet()) {
                mRequestBuilder.addHeader(key, Objects.requireNonNull(headerParams.get(key)));
            }
            return chain.proceed(mRequestBuilder.build());
        };
    }



    public static String calcSign(Map<String, String> headerParams, Request request) {
        Map<String, String> params = new HashMap<>();
        if (request.method().equals("GET")) {
            HttpUrl url = request.url();
            Iterator var11 = url.queryParameterNames().iterator();

            while (var11.hasNext()) {
                String str = (String) var11.next();
                params.put(str, url.queryParameter(str));
            }
        } else if (request.method().equals("POST")) {

            if (request.body() instanceof FormBody) {
                FormBody body = (FormBody) request.body();
                for (int i = 0; i < body.size(); ++i) {
                    params.put(body.name(i), body.value(i));
                }
            }

        } else {
            return null;
        }
        params.putAll(headerParams);
        return sortMapMD5(params, "756fc1i5028q7d17u2e2ic913elca236");
    }

    public static String sortMapMD5(Map<String, String> map, String key) {
        List<Map.Entry<String, String>> infos = new ArrayList<>(map.entrySet());
        Collections.sort(infos, (o1, o2) -> (o1.getKey().compareTo(o2.getKey())));

        char enter = 10;
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < infos.size(); i++) {
            Map.Entry<String, String> ent = infos.get(i);
            String value = ent.getValue();

            sb.append(ent.getKey() + "=" + value + "&");
        }
        sb.append("key=" + key);

        String md5 = org.apache.commons.lang3.StringUtils.lowerCase(getMessageDigest(sb.toString().getBytes()).toString());
        //  String md52 = org.apache.commons.lang3.StringUtils.lowerCase(getMessageDigest(sb.toString().getBytes()).toString());
        return md5;

    }

}
